package cn.edu.nks.dormitory.login.dbimpl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Date;

import org.apache.log4j.Logger;

import cn.edu.nks.dormitory.login.db.IDBService;
import cn.edu.nks.dormitory.model.UserInfo;
import cn.edu.nks.util.DBConnectProvider;


public class DBService implements IDBService{
	private static Logger logger = Logger.getLogger(DBService.class);
	
	public UserInfo selectUserByUnameAndPsw(String userName, String passWord) {
		Connection con = null;
		PreparedStatement stmt = null;
		ResultSet rs = null;
		UserInfo item = null;
		
		con = DBConnectProvider.getConnection();
		if(null == con){
			logger.warn("get connect faild");
			return null;
		}
		StringBuffer sql = new StringBuffer();
		sql.append("select * from userinfo where  username = ? and password = ?");
		try {
			stmt = con.prepareStatement(sql.toString());
			stmt.setString(1, userName);
			stmt.setString(2, passWord);
			rs = stmt.executeQuery();
			if(rs.next()){
				item = new UserInfo();
				item.setUserName(rs.getString("username"));
				item.setUserId(rs.getInt("userid"));
				item.setUserCode(rs.getString("usercode"));
				item.setTime(new Date(rs.getTimestamp("time").getTime()));
				item.setTelephone(rs.getString("telephone"));
				item.setRoleId(rs.getInt("roleid"));
				item.setRealName(rs.getString("realname"));
				item.setPassWord(rs.getString("password"));
				item.setJsons(rs.getString("jsons"));
				item.setEmail(rs.getString("email"));
			}
		} catch (SQLException e) {
			logger.warn(String.format("selectUserByUnameAndPsw error", e));
		}
		DBConnectProvider.freeConnection(con);
		
		return item;
	}

}
